package com.xbongbong.saas.help.workflow;

import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.elasticsearch.model.PaasEsModel;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.pro.domain.entity.UpdateDataEntity;
import com.xbongbong.saas.domain.entity.ProductStockUpdateEntity;
import com.xbongbong.saas.domain.entity.ext.ProductEntityExt;
import com.xbongbong.saas.enums.business.ProductEnum;
import com.xbongbong.saas.model.ProductModel;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.support.WriteRequest;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 *
 * @author 魏荣杰
 *
 */
@Component
@Slf4j
public class WorkflowProductHelp {
    @Resource
    private ProductModel productModel;
    @Resource
    private PaasEsModel paasEsModel;

    public void updateProductStock(Map<Long, ProductStockUpdateEntity> productAddMap, String corpid) throws XbbException {
        if (productAddMap.isEmpty()){
            return;
        }
        productModel.updateStockDB(productAddMap.keySet(),productAddMap.values(),corpid);
        List<ProductEntityExt> productEntityExtList = productModel.getProductListByIdIn(corpid,new ArrayList<>(productAddMap.keySet()), DelEnum.NORMAL.getDel());
        List<UpdateDataEntity> updateList = new ArrayList<>();
        for (ProductEntityExt entityExt : productEntityExtList) {
            JSONObject data = new JSONObject();
            data.put(ProductEnum.COST.getAttr(),entityExt.getData().getDouble(ProductEnum.COST.getAttr()));
            data.put(ProductEnum.STOCK.getAttr (),entityExt.getData().getDouble(ProductEnum.STOCK.getAttr()));
            data.put(ProductEnum.WAREHOUSE_LINK_TEXT.getAttr (),entityExt.getData().get(ProductEnum.WAREHOUSE_LINK_TEXT.getAttr()));
            data.put(ProductEnum.WAREHOUSE.getAttr (),entityExt.getData().get(ProductEnum.WAREHOUSE.getAttr()));
            updateList.add(ExplainUtil.getUpdateData(entityExt.getId(),data,corpid));
        }
        paasEsModel.updateBatchMuchField(updateList, IndexTypeEnum.IDX_SAAS_PRODUCT, WriteRequest.RefreshPolicy.NONE);
    }
}
